package com.uqpsoftware.uqplist;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.uqpsoftware.uqplist.tabs.TaskListFragment;

public class TabsAdapter extends FragmentPagerAdapter implements
		ActionBar.TabListener, ViewPager.OnPageChangeListener {
	private final Context mContext;
	private final ActionBar mActionBar;
	private final ViewPager mViewPager;
	private final ActionBarTabs mActionBarTabs;
	private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
	public FragmentActivity mActivity;
	public Tab currentlySelectedTab;
	private List<Fragment> mAssociatedFragments = new ArrayList<Fragment>();
	private final DataPersistence mDataPersistence;

	// boolean to stop on tab reselected from being called constantly
	private Boolean justCalledTabSelected = false;
	private Boolean justCalledOnPageScrolled = false;
	private Boolean finishedCreatingTabs = false;

	private GoogleAnalyticsTracker mTracker;

	static final class TabInfo {
		private final Class<?> clss;
		private final Bundle args;
		private final int ID;
		private final String name;

		TabInfo(Class<?> _class, Bundle _args, int _ID, String _name) {
			clss = _class;
			args = _args;
			ID = _ID;
			name = _name;
		}
	}

	public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager,
			GoogleAnalyticsTracker tracker) {
		super(activity.getSupportFragmentManager());
		mContext = activity;
		mActionBarTabs = (ActionBarTabs) activity;
		mActivity = activity;
		mActionBar = activity.getSupportActionBar();
		mViewPager = pager;
		mViewPager.setAdapter(this);
		mViewPager.setOnPageChangeListener(this);
		mDataPersistence = DataPersistence.get(mContext);
		mTracker = tracker;

	}

	public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args, int ID,
			String name) {
		TabInfo info = new TabInfo(clss, args, ID, name);
		tab.setTag(info);
		tab.setTabListener(this);
		mTabs.add(info);
		mActionBar.addTab(tab);
		currentlySelectedTab = tab;
		notifyDataSetChanged();
	}

	public void removeTab(ActionBar.Tab tab) {

		// FragmentTransaction fragmentTransaction = mActivity
		// .getSupportFragmentManager().beginTransaction();
		// for (Fragment f : mAssociatedFragments) {
		// fragmentTransaction.remove(f);
		// }
		// fragmentTransaction.commit();
		// destroyItem(mViewPager, tab.getPosition(), fragmentToRemove);

		mTabs.remove(tab.getTag());
		mActionBar.removeTab(tab);
		notifyDataSetChanged();

	}

	public void selectTab(int tabID) {
		Tab tab = getTabFromID(tabID);
		if (tab == null) {
			return;
		}
		mActionBar.selectTab(tab);
	}

	@Override
	public int getItemPosition(Object object) {
		return POSITION_NONE;
	}

	@Override
	public int getCount() {
		return mTabs.size();
	}

	@Override
	public Fragment getItem(int position) {
		TabInfo info = mTabs.get(position);
		Fragment newFragment = Fragment.instantiate(mContext,
				info.clss.getName(), info.args);
		mAssociatedFragments.add(newFragment);
		return newFragment;
	}

	@Override
	public void onPageScrolled(int position, float positionOffset,
			int positionOffsetPixels) {
		justCalledTabSelected = false;
	}

	@Override
	public void onPageSelected(int position) {
		mActionBar.setSelectedNavigationItem(position);
	}

	@Override
	public void onPageScrollStateChanged(int state) {
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		Util.debugToast(mContext, "on Tab Selected " + getTabID(tab));
		currentlySelectedTab = tab;
		justCalledTabSelected = true;

		Object tag = tab.getTag();

		for (int i = 0; i < mTabs.size(); i++) {
			if (mTabs.get(i) == tag) {
				mViewPager.setCurrentItem(i);
				mDataPersistence.persistSelectedTab(mTabs.get(i).ID);
				return;
			}
		}
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		// TODO Auto-generated method stub
		super.destroyItem(container, position, object);
		FragmentManager manager = ((Fragment) object).getFragmentManager();
		FragmentTransaction trans = manager.beginTransaction();
		trans.remove((Fragment) object);
		trans.commit();
	}

	public Integer getTabID(Tab tab) {
		if (tab == null) {
			return null;
		}
		Object tag = tab.getTag();

		for (int i = 0; i < mTabs.size(); i++) {
			if (mTabs.get(i) == tag) {
				return mTabs.get(i).ID;
			}
		}
		return null;
	}

	public Tab getTabFromID(int ID) {
		for (int i = 0; i < mTabs.size(); ++i) {
			if (mTabs.get(i).ID == ID) {
				return mActionBar.getTabAt(i);
			}
		}
		return null;
	}

	public String getTabName(Tab tab) {
		Object tag = tab.getTag();

		for (int i = 0; i < mTabs.size(); i++) {
			if (mTabs.get(i) == tag) {
				return mTabs.get(i).name;
			}
		}
		return null;
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
	}

	@Override
	public void onTabReselected(final Tab tab, FragmentTransaction ft) {
		if (justCalledTabSelected) {
			justCalledTabSelected = false;
			return;
		}
		// if (!finishedCreatingTabs) {
		// return;
		// }
		// if (justCalledTabSelected && justCalledOnPageSelected) {
		Util.debugToast(mContext, "on tab REselected " + getTabID(tab));
		CharSequence[] options = { "Rename List", "Uncheck All" };
		final AlertDialog newTabDialog = new AlertDialog.Builder(mContext)
				.setItems(options, new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (which == 0) {
							renameListDialog(tab);
						} else if (which == 1) {
							uncheckAll(tab);
						}
					}
				}).show();
		// }
	}

	public int numberOfTabs() {
		return mTabs.size();
	}

	private void renameListDialog(final Tab tab) {
		final TabList selectedTab = mActionBarTabs
				.getTabListFromID(getTabID(tab));
		if (selectedTab == null) {
			return;
		}
		final EditText tabNameEditText = new EditText(mContext);
		String tabName = selectedTab.getName();
		tabNameEditText.setText(tabName);
		tabNameEditText.setSelection(tabName.length());
		final AlertDialog newTabDialog = new AlertDialog.Builder(mContext)
				.setTitle("Rename this List")
				.setView(tabNameEditText)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int ignored) {
						String newName = tabNameEditText.getText().toString();
						if (newName.equals("")) {
							return;
						}
						tab.setText(newName);
						selectedTab.setName(newName);
						mDataPersistence.persistTab(selectedTab);
					}

				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int ignored) {
								// TODO Auto-generated method stub

							}
						}).show();
		newTabDialog.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
	}

	private void uncheckAll(Tab tab) {
		TaskListFragment tlf = mActionBarTabs.getFragmentWithID(getTabID(tab));
		tlf.uncheckAllTasks();
	}

	public void setTabCreationFinishedStatus(Boolean creationStatus) {
		finishedCreatingTabs = creationStatus;
	}

}
